package cn.ddiancan.auth.service.enhancer;

import java.util.Objects;

import cn.ddiancan.auth.context.AuthContext;
import cn.ddiancan.xddcloud.common.entity.UserVO;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.server.authorization.token.JwtEncodingContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer;
import org.springframework.util.StringUtils;

@Slf4j
@RequiredArgsConstructor
public class XddCustomTokenEnhancer implements OAuth2TokenCustomizer<JwtEncodingContext> {

    @Override
    public void customize(JwtEncodingContext context) {
        try {
            UserVO pscUser = AuthContext.getAuthUser();
            log.info("XddCustomTokenEnhancer load threadlocal user:{}", Objects.nonNull(pscUser) ? pscUser.getUserAccount() : null);
            if (StringUtils.hasText(pscUser.getUserAccount())) {
                context.getClaims().claims(claims -> {
                    claims.put("userName", pscUser.getUserName());
                    claims.put("userAccount", pscUser.getUserAccount());
                    claims.put("content", JSON.toJSONString(pscUser));
                    claims.put("authorities", pscUser.getUserPermissions());
                });
            }
        } catch (Exception e) {
            log.error("XddCustomTokenEnhancer customize error", e);
        } finally {
            AuthContext.clearAuthUser();
        }
    }
}
